//
//  File.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/24.
//

import Foundation
import Vapor

struct FeedBack: RouteCollection {
    func boot(routes: any RoutesBuilder) throws {
        let group = routes.grouped("feedback")
        group
            .post("add", use: self.add)
    }
    
    @Sendable
    func add(request: Request) async throws -> JSONResponse<Bool> {
        // 定义请求参数结构
        struct FeedbackParam: Content {
            let suggestion: String
        }
        
        // 获取用户ID
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        
        // 解码请求参数
        let param = try request.content.decode(FeedbackParam.self)
        
        // 验证反馈内容
        guard !param.suggestion.isEmpty else {
            return JSONResponse(message: "反馈内容不能为空", code: -1, data: false)
        }
        
        // 创建反馈记录
        let feedback = FeedbackModel(
            id: UUID(),
            userID: deviceID,
            suggestion: param.suggestion,
            createDate: Date()
        )
        
        // 保存到数据库
        try await feedback.save(on: request.db)
        
        return JSONResponse(
            message: "反馈提交成功",
            code: 0,
            data: true
        )
    }
}
